import { Toast } from "@/utils/index";

export const downloadFiles = function(urls: string[]) {
  checkAuth(() => {
    uni.showLoading({
      title: '下载中...',
      mask: true
    })
    for (let i = 0; i < urls.length; i++) {
      downloadSaveFile(urls[i]);
    }
  })
}

//下载文件
const downloadSaveFile = function(url: string) {
  const imgType = ['jpg','png','svg','jpeg','gif'];
  const fileType = url.split('.').slice(-1);
  if (imgType.includes(fileType[0])) { // 图片类型
    uni.downloadFile({
      url: url,
      success: res => {
        if (res.statusCode === 200) {
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: res => {
              Toast('下载成功');
            },
            fail: res => {
              Toast('下载失败');
            }
          })

        }
      }
    })

  }
}

//检查权限
function checkAuth(gotc: any) {
  uni.getSetting({
    success(res) {
      uni.hideLoading();
      if (!res.authSetting['scope.writePhotosAlbum']) {
        //请求授权
        uni.authorize({
          scope: 'scope.writePhotosAlbum',
          success() {
            //获得授权，开始下载
            gotc && gotc();
          },
          fail() {
            uni.showModal({
              title: '提示',
              content: '保存到系统相册需要授权',
              confirmText: '立即授权',
              success(res) {
                if (res.confirm) {
                  uni.openSetting({
                    success(res) {
                      if (res.authSetting['scope.writePhotosAlbum'] === true) {
                        gotc && gotc();
                      }
                    }
                  })
                }
              },
              fail() {
                Toast('打开设置页失败');
              }
            })
          }
        })
      } else {
        //已有授权
        gotc && gotc();
      }
    },
    fail() {
      Toast('获取授权失败');
    }
  })
}